package org.fly.jingwei.service.impl;


import cn.hutool.core.util.StrUtil;
import net.sf.json.JSONObject;
import org.fly.jingwei.bean.PageForBean;
import org.fly.jingwei.dao.UserDao;
import org.fly.jingwei.dao.UserGroupDao;
import org.fly.jingwei.entity.UserEntity;
import org.fly.jingwei.entity.UserGroupAttributeEntity;
import org.fly.jingwei.exception.JingWeiSysException;
import org.fly.jingwei.service.UserService;
import org.fly.jingwei.util.HttpServletUtil;
import org.fly.jingwei.util.KettleEncrypt;
import org.fly.jingwei.util.StringDateUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author leo.jie (weixiao.me@aliyun.com)
 * @version 1.0
 * @organization bigdata
 * @website https://www.jielongping.com
 * @date 2020/5/28 11:30 下午
 * @since 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserDao userDao;

    private final UserGroupDao userGroupDao;

    public UserServiceImpl(UserDao userDao, UserGroupDao userGroupDao) {
        this.userDao = userDao;
        this.userGroupDao = userGroupDao;
    }

    @Override
    public void deleteUser(Integer id, String username) {
        userGroupDao.deleteUserAttributeByName(username);
        userDao.deleteUser(id);
    }

    @Override
    public void updateUser(UserEntity user, UserGroupAttributeEntity attr) {
        //修改用户
        if (!StrUtil.isBlank(user.getDescription())) {
            userDao.updateUser(user);
            //被修改的用户需要重新登录 使其session失效
            List<String> invalidSession = new ArrayList<>();
            Set<String> set = StringDateUtil.allSession.keySet();
            for (String sessionId : set) {
                HttpSession session = StringDateUtil.allSession.get(sessionId);
                if (null != session.getAttribute("login")) {
                    UserEntity iUser = (UserEntity) session.getAttribute("login");
                    if (iUser.getUserId().intValue() == user.getUserId().intValue()) {
                        invalidSession.add(session.getId());
                    }
                }
            }
            for (String invalid : invalidSession) {
                HttpSession httpSession = StringDateUtil.allSession.get(invalid);
                StringDateUtil.allSession.remove(invalid);
                httpSession.invalidate();
            }
        }
        //修改用户与用户组关系表中 节点任务组的权限
        if (null != attr) {
            userGroupDao.updateUserGroupAttrByName(attr);
        }
    }

    @Override
    public boolean addUser(UserEntity user, UserGroupAttributeEntity attribute) {
        attribute.setCreateDate(new Date());
        List<UserEntity> allUser = userDao.getAllUsers();
        for (UserEntity item : allUser) {
            if (item.getLogin().equals(user.getLogin())) {
                return false;
            }
        }
        Integer userId = userDao.selectMaxId();
        if (null != userId) {
            userId += 1;
        } else {
            userId = 0;
        }
        user.setUserId(userId);
        userDao.addUser(user);
        userGroupDao.addUserGroupAttribute(attribute);
        return true;
    }

    @Override
    public String getUsersLimit(int start, int limit, HttpServletRequest request) {
        String username = request.getParameter("username");
        String userType = request.getParameter("usertype");
        String userGroup = request.getParameter("usergroup");
        //获取当前用户所在的用户组
        UserGroupAttributeEntity userAttribute = (UserGroupAttributeEntity) request.getSession().getAttribute("userInfo");
        String userGroupName = userAttribute.getUserGroupName();
        //如果是admin用户则把查询条件赋给该值
        if (StringDateUtil.isEmpty(userGroupName)) {
            userGroupName = userGroup;
        }
        //获取用户类型
        Integer userTypeI = null;
        if ("管理员".equals(userType)) {
            userTypeI = 1;
        } else if ("普通用户".equals(userType)) {
            userTypeI = 2;
        }
        //获取用户集合    总记录数
        List<UserEntity> users;
        Integer count = userDao.getUserCount(userGroupName);
        users = userDao.getUsersLimit(start, limit, userGroupName, username, userTypeI);
        //如果不是是admin用户 把该用户组下面所有用户权限为1的用户移除
        if (!StringDateUtil.isEmpty(userGroupName)) {
            List<UserEntity> adminUserArray = new ArrayList<>();
            for (UserEntity user : users) {
                user.setPassword(KettleEncrypt.decryptPassword(user.getPassword()));
                if (user.getUserType() == 1) {
                    adminUserArray.add(user);
                }
            }
            for (UserEntity adminUser : adminUserArray) {
                users.remove(adminUser);
                count--;
            }
        } else {
            count--;
            for (UserEntity user : users) {
                user.setPassword(KettleEncrypt.decryptPassword(user.getPassword()));
            }
        }

        PageForBean<UserEntity> bean = new PageForBean<>();
        bean.setRoot(users);
        bean.setTotalProperty(count);
        return JSONObject.fromObject(bean, StringDateUtil.configJson("yyyy-MM-dd HH:mm:ss")).toString();
    }

    @Override
    public List<UserEntity> getUserByName(String login) {
        return userDao.getUserByName(login);
    }

    @Override
    public void login(String userName, String password) {
        if (StrUtil.isBlank(userName)) {
            throw new JingWeiSysException("用户名不能为空");
        }
        if (StrUtil.isBlank(password)) {
            throw new JingWeiSysException("密码不能为空");
        }
        List<UserEntity> users = this.getUserByName(userName);
        if (users.isEmpty()) {
            throw new JingWeiSysException("用户名不存在");
        } else {
            UserEntity user = users.get(0);
            String realPassword = KettleEncrypt.decryptPassword(user.getPassword());
            if (!realPassword.equals(password)) {
                throw new JingWeiSysException("密码输入错误");
            } else {
                if (null == HttpServletUtil.getCurrentLoginUser()) {
                    user.setPassword(KettleEncrypt.decryptPassword(users.get(0).getPassword()));
                    UserGroupAttributeEntity attribute = userGroupDao.getInfoByUsername(userName);
                    if (null == attribute) {
                        attribute = new UserGroupAttributeEntity();
                    }
                    HttpServletUtil.saveUserInfoSession(user, attribute);
                }
            }
        }
    }

    @Override
    public void allotUserGroup(UserGroupAttributeEntity attr) {
        userGroupDao.updateUserGroupAttrByName(attr);
        //用户状态发生改变使session失效
        List<String> invalidSession = new ArrayList<>();
        Set<String> set = StringDateUtil.allSession.keySet();
        for (String sessionId : set) {
            HttpSession session = StringDateUtil.allSession.get(sessionId);
            if (null != session.getAttribute("login")) {
                UserEntity iUser = (UserEntity) session.getAttribute("login");
                if (iUser.getLogin().equals(attr.getUserName())) {
                    invalidSession.add(session.getId());
                }
            }
        }
        for (String invalid : invalidSession) {
            HttpSession httpSession = StringDateUtil.allSession.get(invalid);
            StringDateUtil.allSession.remove(invalid);
            httpSession.invalidate();
        }
    }

    @Override
    public List<UserEntity> getUsers(String userGroupName) {
        return userDao.getUsers(userGroupName);
    }

    @Override
    public void updatePassword(UserEntity user) {
        userDao.updateUser(user);
    }
}
